﻿using System;
using System.Xml;

namespace BasecampRestAPI
{
	//<time-entry>
	//  <id type="integer">#{id}</id>
	//  <project-id type="integer">#{project-id}</project-id>
	//  <person-id type="integer">#{person-id}</person-id>
	//  <date type="date">#{date}</date>
	//  <hours>#{hours}</hours>
	//  <description>#{description}</description>
	//  <todo-item-id type="integer">#{todo-item-id}</todo-item-id>
	//</time-entry>
	public class TimeEntry : ITimeEntry
	{
		private readonly int _projectId;
		private IProject _project;
		private readonly int _personId;
		private IPerson _person;
		private readonly int _toDoItemId;
		private IToDoListItem _toDoListItem;

		public static TimeEntry GetInstance(IBaseCamp camp, XmlNode node)
		{
			return new TimeEntry(camp, node);
		}
		private TimeEntry(IBaseCamp camp, XmlNode node)
		{
			Camp = camp;
			Id = XmlHelpers.ParseInteger(node, "id");
			_projectId = XmlHelpers.ParseInteger(node, "project-id");
			_personId = XmlHelpers.ParseInteger(node, "person-id");
			Date = XmlHelpers.ParseDateTime(node, "date");
			Hours = double.Parse(XmlHelpers.ChildNodeText(node, "hours"));
			Description = XmlHelpers.ChildNodeText(node, "description");
			_toDoItemId = XmlHelpers.ParseInteger(node, "todo-item-id");
		}
		private IBaseCamp Camp { get; set; }

		#region Implementation of ITimeEntry
		public int Id { get; private set; }
		public DateTime Date { get; private set; }
		public double Hours { get; private set; }
		public string Description { get; private set; }
		public IProject Project
		{
			get
			{
				if (_project == null)
				{
					_project = Camp.GetProjectById(_projectId);
				}
				return _project;
			}
		}
		public IPerson Person
		{
			get
			{
				if (_person == null)
				{
					_person = Camp.GetPersonById(_personId);
				}
				return _person;
			}
		}
		public IToDoListItem ToDoListItem
		{
			get
			{
				if (_toDoListItem == null)
				{
					_toDoListItem = Camp.GetToDoListItemById(_toDoItemId);
				}
				return _toDoListItem;
			}
		}

		#endregion
	}
}
